package com.ctsi.security.app.controller;

import com.ctsi.commons.util.UtilValidate;
import com.ctsi.commons.util.request.UtilHttp;
import com.ctsi.commons.util.response.Page;
import com.ctsi.framework.common.response.UnifiedResponse;
import com.ctsi.framework.security.util.SecurityUtil;
import com.ctsi.security.ISecurity;
import com.ctsi.security.PermissionTypeSer;
import com.ctsi.security.domain.DataObject;
import com.ctsi.security.domain.DataObjectType;
import com.ctsi.security.domain.Permission;
import com.ctsi.security.service.DataObjectService;
import com.ctsi.security.service.DataObjectTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
public class DoTypeController {
	private static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(DoTypeController.class);
	@Autowired
	private DataObjectTypeService dataObjectTypeService;
    @Autowired
	private DataObjectService dataObjectService;
    @Autowired
	private PermissionTypeSer permissionTypeService;
	private final static String SYSTEMDATAOBJECTTYPE = "systemDataObjectType";
    @Autowired
	private ISecurity iSecurity;

	private String secretTypeId = "DataObjectTypeSecret-Manager";


	/** *********************数据对象类型CRUD************start********************************* */
	public ModelAndView viewDoType(HttpServletRequest request, HttpServletResponse respone) {
		return new ModelAndView("security/doType/doType");
	}

    /**
     * 查询数据对象类型 1
     * @param request
     * @param response
     * @return
     */
    @PostMapping(value = "/security/data-object-types")
	public UnifiedResponse<Page<DataObjectType>> doTypePage(HttpServletRequest request, HttpServletResponse response) {
		int skipResults = 0;
		int pageSize = Page.DEFAULT_PAGE_SIZE;
		String start = request.getParameter("start");
		String limit = request.getParameter("limit");
		if (UtilValidate.isNotEmpty(limit)) {
			pageSize = Integer.parseInt(limit);
		}
		if (UtilValidate.isNotEmpty(start))
			skipResults = Integer.parseInt(start);

		List<Permission> listPermission = this.permissionTypeService.findAllChildPermision(this.secretTypeId, SecurityUtil.getUser().getLoginId());
		List<String> listStr = new ArrayList<String>();
		for (Permission permission : listPermission) {
			if (iSecurity.hasPermission(SecurityUtil.getUser().getLoginId(), permission.getPermissionId()))
				listStr.add(permission.getPermissionId());
		}
		Page<DataObjectType> page = dataObjectTypeService.queryDataObjectType(pageSize, skipResults, UtilHttp.filterBlank(UtilHttp.getParameterMap(request)), listStr);
		return UnifiedResponse.ok(page);
	}

//	// 打开添加数据对象类型
//	public ModelAndView addDoType(HttpServletRequest request, HttpServletResponse response) {
//
//		ModelAndView modelAndView = new ModelAndView("security/doType/addDoType");
//
//		modelAndView.addObject("secretTypeId", getSecretTypeId(request));
//		return modelAndView;
//	}
//	public ModelAndView addDoType1(HttpServletRequest request, HttpServletResponse response) {
//		List<Permission> listPermission = this.permissionTypeService.findAllChildPermision(this.secretTypeId, super.getCuruserLoginId(request));
//		String listText = "请选择数据对象";
//		String listValue = " ";
//		for (Permission permission : listPermission) {
//			listText = listText + "," + permission.getPermissionName();
//			listValue = listValue + "," + permission.getPermissionId();
//		}
//		request.setAttribute("listText", listText);
//		request.setAttribute("listValue", listValue);
//		ModelAndView modelAndView = new ModelAndView("security/doType/addDoType");
//		return modelAndView;
//	}
//
	private String getSecretTypeId(HttpServletRequest request) {
		List<Permission> listPermission = this.permissionTypeService.findAllChildPermision(this.secretTypeId, SecurityUtil.getUser().getLoginId());
		StringBuilder secretTypeId = new StringBuilder("{[");
		secretTypeId.append("[").append("'请选择数据对象','']");
		secretTypeId.append(",");
		for (Permission permission : listPermission) {
			secretTypeId.append("[").append("'").append(permission.getPermissionName());
			secretTypeId.append("','");
			secretTypeId.append(permission.getPermissionId());
			secretTypeId.append("']");
			secretTypeId.append(",");
		}
		if (secretTypeId.lastIndexOf(",") != -1)
			secretTypeId.deleteCharAt(secretTypeId.length() - 1);
		secretTypeId.append("]}");
		logger.info("分级授权功能权限  {} ", secretTypeId);
		return secretTypeId.toString();
	}
//
//	// 保存数据对象类型
//	public ModelAndView saveDoType(HttpServletRequest request, HttpServletResponse response) {
//		return this.saveOrUpdateDoType(request, response);
//	}
//
//

	/**
	 * 禁用或启用数据对象  1
	 * @param id
	 * @param status
	 * @return
	 */
	@PutMapping(value = "/dataobject-type/status/{id}")
	public UnifiedResponse<Void> changeStatus(@PathVariable(value = "id") String id,
											  @RequestParam(value = "status") Integer status){
		DataObjectType doType = dataObjectTypeService.findById(id);
		doType.setStatus(status);
		logger.info("数据对象类型状态为{}", status);
		dataObjectTypeService.updateDataObjectType(doType);
		return UnifiedResponse.ok();
	}

	/**
	 * 保存和更新数据对象类型
	 * @param request
	 * @param response
	 * @return
	 */
	@PostMapping(value = "/dataobject-type/save-update")
	public UnifiedResponse<Void> saveOrUpdateDoType(HttpServletRequest request, HttpServletResponse response) {

		String id = request.getParameter("ID");
		id = id == null ? "" : id;
		String doTypeId = request.getParameter("doTypeId");
		doTypeId = doTypeId == null ? "" : doTypeId;
		String doTypeName = request.getParameter("doTypeName");
		doTypeName = doTypeName == null ? "" : doTypeName;
		String description = request.getParameter("description");
		description = description == null ? "" : description;
		// 判断状态
		String status = request.getParameter("status");

		// 分级授权功能
		String secretTypeId = request.getParameter("secretTypeId");

		secretTypeId = UtilValidate.isEmpty(secretTypeId) ? null : secretTypeId;

		if (UtilValidate.isEmpty(status)) {
			status = Integer.toString(DataObjectType.FORBIDDEN);
		}
		// 得到数据对象的类型
		String category = request.getParameter("category");
		if (UtilValidate.isNotEmpty(category)) {
			logger.info("****************The category is {}", category);
		} else {
			category = "0";
		}

		String actionDic = request.getParameter("actionDic");
		actionDic = actionDic == null ? "" : actionDic;

		DataObjectType doType = new DataObjectType();
		doType.setId(id);
		doType.setDataObjectTypeId(doTypeId);
		doType.setDataObjectTypeName(doTypeName);
		doType.setDescription(description);
		doType.setStatus(Integer.parseInt(status));
		doType.setCategory(category);
		doType.setActionDic(actionDic);
		doType.setSecretTypeId(secretTypeId);
		logger.info("数据对象类型状态为{}", status);

		if (id.equals("")) {
			if (dataObjectTypeService.valDataObjectTypeId(doTypeId)) {
				return UnifiedResponse.error("-1", "数据库中已存在该ID，请重新填写!");
			} else {
				dataObjectTypeService.saveDataObjectType(doType);
			}
		} else {
			dataObjectTypeService.updateDataObjectType(doType);
		}
		return UnifiedResponse.ok();
	}
//
	// 打开修改数据对象类型页面
//	public ModelAndView editDoType(HttpServletRequest request, HttpServletResponse response) {
//		String ID = request.getParameter("ID");
//		ID = ID == null ? "" : ID;
//		DataObjectType doType = null;
//		List<DataObjectType> listDoType = dataObjectTypeService.findDataObjectType(new String[] { "ID" }, new Object[] { ID });
//		if (listDoType.size() > 0) {
//			doType = listDoType.get(0);
//		} else {
//			doType = new DataObjectType();
//		}
//
//		ModelAndView modelAndView = new ModelAndView("security/doType/editDoType");
//		modelAndView.addObject("secretTypeId", getSecretTypeId(request));
//		modelAndView.addObject("doType", doType);
//		return modelAndView;
//	}
//
//	// 删除数据对象类型
//	public ModelAndView delDoType(HttpServletRequest request, HttpServletResponse response) {
//		String IDS = request.getParameter("IDS");
//		IDS = IDS == null ? "" : IDS;
//		String[] arrayId = IDS.substring(0, IDS.lastIndexOf(",")).split(",");
//		String doTypeIds = request.getParameter("doTypeIds");
//		doTypeIds = doTypeIds == null ? "" : doTypeIds;
//		String[] arrayDoTypeId = doTypeIds.split(",");
//		int i = 0;
//		try {
//			i = dataObjectTypeService.removeDataObjectType(arrayId, arrayDoTypeId);
//			if (i > -1){
//				throw new Exception("数据对象类型" + arrayDoTypeId[i] + "下有数据对象，不能删除");
//			}
//			super.setReturnMsg(request, "删除成功");
//		} catch (Exception e) {
//			logger.info("数据对象类型{}有数据对象，不能删除", arrayDoTypeId[i]);
//			super.SetErrMsg(request, "数据对象类型" + arrayDoTypeId[i] + "下有数据对象，不能删除");
//		}
//		return new ModelAndView("security/doType/doType");
//	}
//

//    /**
//     * 查看数据对象类型下的数据对象
//     * @param request
//     * @param respone
//     * @return
//     */
//	public ModelAndView viewDoTypeDo(HttpServletRequest request, HttpServletResponse respone) {
//		String doTypeId = request.getParameter("doTypeId");
//		doTypeId = doTypeId == null ? "" : doTypeId;
//		String doTypeName = "";
//
//		String url = request.getParameter("url");
//		url = url == null ? "security/doType/doTypeDo" : url;
//		// 根据ID查询名称
//		List<DataObjectType> listDoType = dataObjectTypeService.findDataObjectType(new String[] { "dataObjectTypeId" }, new Object[] { doTypeId });
//		if (listDoType.size() > 0) {
//			doTypeName = listDoType.get(0).getDataObjectTypeName();
//		}
//		request.setAttribute("doTypeId", doTypeId);
//		request.setAttribute("doTypeName", doTypeName);
//		String parent = request.getParameter("parent");
//		if (UtilValidate.isEmpty(parent)) {
//			String thisid = request.getParameter("thisid");
//			DataObject dataObject = dataObjectService.findByDataObjectId(thisid);
//			parent = dataObject.getParent();
//		}
//		request.setAttribute("parent", parent);
//
//		return new ModelAndView(url);
//	}



//

    /**
     * 查询数据对象类型下的数据对象 1
     * @param request
     * @param response
     * @return
     */
    @PostMapping(value = "/security/view-dataobjects")
	public UnifiedResponse<Page<DataObject>> doTypeDoPage(HttpServletRequest request, HttpServletResponse response) {
		int skipResults = 0;
		int pageSize = Page.DEFAULT_PAGE_SIZE;
		String start = request.getParameter("start");
		String limit = request.getParameter("pageSize");
		if (UtilValidate.isNotEmpty(limit)) {
			pageSize = Integer.parseInt(limit);
		}
		if (UtilValidate.isNotEmpty(start))
			skipResults = Integer.parseInt(start);
		Map<String, Object> param = UtilHttp.filterBlank(UtilHttp.getParameterMap(request));
		String dataobjecttypeid = (String) param.get("dataobjecttypeid");
		String parent = (String) param.get("parent");
		if ((UtilValidate.isNotEmpty(dataobjecttypeid) && dataobjecttypeid.equals(param.get("parent"))) || UtilValidate.isEmpty(parent)) {
			param.remove("parent");
			param.put("root", true);
		}
		Page<DataObject> page = dataObjectService.queryDataObject(SecurityUtil.getUser().getLoginId(), SYSTEMDATAOBJECTTYPE, "SELECT", pageSize, skipResults, param);
		return UnifiedResponse.ok(page);
	}
//
//	// 打开添加数据对象类型
//	public ModelAndView addDoTypeDo(HttpServletRequest request, HttpServletResponse response) {
//		String doTypeId = request.getParameter("doTypeId");
//		doTypeId = doTypeId == null ? "" : doTypeId;
//		request.setAttribute("doTypeId", doTypeId);
//		Long maxNo = this.dataObjectService.getMaxOrderNo();
//		request.setAttribute("maxOrderNo", maxNo + 100);
//		return new ModelAndView("security/doType/addDoTypeDo");
//	}
//
//	// 保存数据对象类型下数据对象
//	public ModelAndView saveDoTypeDo(HttpServletRequest request, HttpServletResponse response) {
//		return this.saveOrUpdateDoTypeDo(request, response);
//	}
//
//	// 更新数据对象类型下数据对象
//	public ModelAndView updateDoTypeDo(HttpServletRequest request, HttpServletResponse response) {
//		return this.saveOrUpdateDoTypeDo(request, response);
//	}
//
//    /**
//     * 保存和更新数据对象类型下数据对象
//     * @param request
//     * @param response
//     * @return
//     */
//	public ModelAndView saveOrUpdateDoTypeDo(HttpServletRequest request, HttpServletResponse response) {
//		DataObject dataObject = bind(request);
//		if (UtilValidate.isEmpty(dataObject.getId())) {
//			try {
//				dataObjectService.saveDataObject(dataObject);
//			} catch (Exception e) {
//				super.SetErrMsg(request, "保存失败，请检查此id是否已存在");
//				return viewDoTypeDo(request, response);
//			}
//		} else {
//			dataObjectService.updateDataObject(dataObject);
//		}
//		super.setReturnMsg(request, "保存成功");
//		request.setAttribute("dataObject", dataObject);
//		return viewDoTypeDo(request, response);
//	}
//
//	// 打开修改数据对象类型下数据对象页面
//	public ModelAndView editDoTypeDo(HttpServletRequest request, HttpServletResponse response) {
//		String ID = request.getParameter("ID");
//		ID = ID == null ? "" : ID;
//		DataObject dataObject = null;
//		List<DataObject> listDataObject = dataObjectService.findDataObject(new String[] { "ID" }, new Object[] { ID });
//		if (listDataObject.size() > 0) {
//			dataObject = listDataObject.get(0);
//		} else {
//			dataObject = new DataObject();
//		}
//		request.setAttribute("dataObject", dataObject);
//		return new ModelAndView("security/doType/editDoTypeDo");
//	}
//
//	// 删除数据对象类型
//	public ModelAndView delDoTypeDo(HttpServletRequest request, HttpServletResponse response) {
//		String IDS = request.getParameter("IDS");
//		IDS = IDS == null ? "" : IDS;
//		String[] arrayId = IDS.substring(0, IDS.lastIndexOf(",")).split(",");
//		String doIds = request.getParameter("doIds");
//		doIds = doIds == null ? "" : doIds;
//		String[] arrayDoIds = doIds.split(",");
//		for (int i = 0; i < arrayId.length; i++) {
//			DataObject dataObject = null;
//			List<DataObject> listDataObject = dataObjectService.findDataObject(new String[] { "ID" }, new Object[] { arrayId[i] });
//			if (listDataObject.size() > 0) {
//				dataObject = listDataObject.get(0);
//			} else {
//				dataObject = new DataObject();
//			}
//			dataObjectService.removeDataObject(arrayId[i], arrayDoIds[i]);
//			String description = "删除数据对象类型"+dataObject.getDataObjectTypeName()+"下的数据对象"+dataObject.getDataObjectName();
//		}
//		return null;
//	}
//
//	public DataObjectTypeService getDataObjectTypeService() {
//		return dataObjectTypeService;
//	}
//
//	public void setDataObjectTypeService(DataObjectTypeService dataObjectTypeService) {
//		this.dataObjectTypeService = dataObjectTypeService;
//	}
//
//	public DataObjectService getDataObjectService() {
//		return dataObjectService;
//	}
//
//	public void setDataObjectService(DataObjectService dataObjectService) {
//		this.dataObjectService = dataObjectService;
//	}
//
//	public void setPermissionTypeService(PermissionTypeSer permissionTypeService) {
//		this.permissionTypeService = permissionTypeService;
//	}
//
//	public DataObject bind(HttpServletRequest request) {
//		DataObject dataobject = new DataObject();
//        Map<String, Object> data = UtilHttp.getParameterMap(request);
//        UtilMisc.copyMapToBean(data, dataobject, true);
//		return dataobject;
//	}
//
//	/** *********************数据对象类型CRUD************end*********************************** */
//	public void setSecretTypeId(String secretTypeId) {
//		this.secretTypeId = secretTypeId;
//	}
}
